//
//  MHMusicCatergoryViewModel.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/10/17.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHMusicCatergoryViewModel.h"
#import "TCBGMHelper.h"
#import "MHAVAudioManager.h"
#import "MHCustomItemViewModel.h"
@implementation MHMusicCatergoryViewModel


-(void)initialize
{
    [super initialize];
    self.shouldPullDownToRefresh = NO;
    self.shouldPullUpToLoadMore = YES;
    
    self.shouldRequestRemoteDataOnViewDidLoad = !self.isSearch;
    @weakify(self);

    self.didSelectCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath * indexPath) {
        @strongify(self);
        /// 这里只是测试
        TCBGMElement *item = self.datas[indexPath.row];
        MHAVAudioManager *manger = [MHAVAudioManager shareManager];
        NSURL *palyUrl = item.dataFromLocal ? item.musicUrl : [NSURL URLWithString:item.fullSongUrl];
        if ([[manger currentUrl] isEqual:palyUrl]) {
            if (manger.isPlaying) {
                [manger pause];
            }else
            {
                [manger play];
            }
        }else
        {
            [manger musicPlayerWithURL:palyUrl];
        }
        return [RACSignal empty];
    }];
    
}

- (instancetype)initWithServices:(id<MHViewModelServices>)services params:(NSDictionary *)params{
    if (self = [super initWithServices:services params:params]) {
        self.categoryId = [params[MHViewModelUtilKey] intValue];
         self.isSearch = [params[MHViewModelCommonModelUtilKey] boolValue];
    }
    return self;
}





- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page{
    
    NSArray * (^mapCircles)(NSArray *) = ^(NSArray *products) {
        if (page == 1) {
            /// 下拉刷新
        } else {
            /// 上拉加载
            products = @[(self.datas ?: @[]).rac_sequence, products.rac_sequence].rac_sequence.flatten.array;
        }
        return products;
    };
    return  [[[self.services.client getSongPagedListWithSongName:self.searchText categoryName:@"" categoryId:self.categoryId pageNum:page pageSize:self.perPage] mh_parsedResults] map:mapCircles];
}

//-(RACSignal *) customSignalWithPage:(NSInteger) page
//{
//    return [RACSignal empty];
//}
#pragma mark - 辅助方法
- (NSArray *)dataSourceWithCircles:(NSArray *)datas {
    if (MHObjectIsNil(datas) || datas.count == 0) return @[];
    NSArray *viewModels = [datas.rac_sequence map:^(TCBGMElement *data) {
        MHCustomItemViewModel *viewModel = [[MHCustomItemViewModel alloc] initWithModel:data];
        [[TCBGMHelper sharedInstance].bgmDict setObject:data forKey:data.fullSongUrl];
        return viewModel;
    }].array;
    return viewModels ?: @[] ;
}



//-(RACSignal *)customSignalWithPage:(NSInteger)page
//{
//    return  ;
//}

@end
